package com.scriptlib;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.media.Image;
import android.util.Log;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class GraphicHelper {
    private byte[] ScreenData;
    private short[][] RedList;
    private int Width = -1;
    private int Height = -1;
    private int RowStride = -1;
    private int _RowStride = -1;
    private boolean IsInit = false;
    private final AJFunc MyAJFunc;
    private final int[] Steps = new int[256];
    private final int[] Lens = new int[256];
    public static GraphicHelper Instance = null;

    public static GraphicHelper GetInstance(Object obj) {
        if (Instance == null) {
            Instance = new GraphicHelper(obj);
        }
        return Instance;
    }

    public GraphicHelper(Object obj) {
        this.MyAJFunc = new AJFunc(obj);
        Init();
    }

    private void Init() {
        Image image = null;
        try {
            image = (Image) MyAJFunc.CaptureMethod.invoke(MyAJFunc.ScreenCapturer);
        } catch (IllegalAccessException | InvocationTargetException e) {
            Log.e("ScriptLib", e.toString());
        }
        if (image == null) {
            return;
        }
        ByteBuffer byteBuf = image.getPlanes()[0].getBuffer();
        Width = image.getWidth();
        Height = image.getHeight();
        RowStride = image.getPlanes()[0].getRowStride();
        ScreenData = new byte[RowStride * Height];
        byteBuf.position(0);
        byteBuf.get(ScreenData, 0, RowStride * Height);
        Arrays.fill(Lens, 10240);
        GetRedList();
    }

    static public String Version() {
        return AJFunc.Version();
    }

    static public String GetInfo() {
        return AJFunc.GetInfo();
    }

    public boolean KeepScreen(boolean sign) {
        if (GetLastFrame()) {
            if (sign) {
                GetRedList();
            }
            return true;
        } else {
            return false;
        }
    }

    private boolean GetLastFrame() {
        Image image = null;
        try {
            image = (Image) MyAJFunc.CaptureMethod.invoke(MyAJFunc.ScreenCapturer);
        } catch (IllegalAccessException | InvocationTargetException e) {
            Log.e("ScriptLib", e.toString());
        }
        if (image == null) {
            return false;
        }
        ByteBuffer byteBuf = image.getPlanes()[0].getBuffer();
        if (!IsInit) {
            IsInit = true;
            Width = image.getWidth();
            Height = image.getHeight();
            RowStride = image.getPlanes()[0].getRowStride();
            ScreenData = new byte[RowStride * Height];
            RedList = new short[256][10240];
        }
        byteBuf.position(0);
        byteBuf.get(ScreenData, 0, RowStride * Height);
        return true;
    }

    /**
     * 获取所有r值对应的坐标,找色效率更快
     */
    private void GetRedList() {
        Arrays.fill(Steps, 0);
        int location;
        for (short i = 0; i < (short) Height; i++) {
            location = RowStride * i;
            for (short j = 0; j < (short) Width; j++) {
                int k = ScreenData[location] & 0xff;
                int step = Steps[k];
                if (step == Lens[k]) {
                    Lens[k] = Lens[k] + 10240;
                    RedList[k] = Arrays.copyOf(RedList[k], Lens[k]);
                }
                RedList[k][step] = j;
                RedList[k][step + 1] = i;
                location += 4;
                Steps[k] = step + 2;
            }
        }
    }

    private int Abs(int num) {
        return (num ^ (num >> 31)) - (num >> 31);
    }

    public byte[] GetScreenData() {
        return ScreenData;
    }

    public String GetPixelStr(int x, int y) {
        int[] result = GetPixel(x, y);
        int color = (result[0] & 0xff) << 16 | (result[1] & 0xff) << 8 | (result[2] & 0xff);
        return String.format("0x%06x", color);
    }

    public int GetPixelInt(int x, int y) {
        int[] result = GetPixel(x, y);
        return (result[0] & 0xff) << 16 | (result[1] & 0xff) << 8 | (result[2] & 0xff);
    }

    public int[] GetPixel(int x, int y) {
        if (x >= 0 && x < Width && y >= 0 && y < Height) {
            int location = x * 4 + y * RowStride;
            int[] result = new int[3];
            result[0] = ScreenData[location] & 0xff;
            result[1] = ScreenData[location + 1] & 0xff;
            result[2] = ScreenData[location + 2] & 0xff;
            return result;
        } else {
            return new int[]{0, 0, 0};
        }
    }

    public boolean CompareColor(int[] description, int sim, int offset) {
        offset = Math.min(offset, 1);
        int x = description[0];
        int y = description[1];
        int size = (offset * 2 + 1) * (offset * 2 + 1);

        int similarity = (int) (255 - 255 * (sim / 100.0));
        int similarity_R = similarity;
        int similarity_G = similarity;
        int similarity_B = similarity;

        if (description.length == 8) {
            similarity_R = similarity + description[5];
            similarity_G = similarity + description[6];
            similarity_B = similarity + description[7];
        }

        Point[] offsetPoint;

        if (offset == 1) {
            offsetPoint = new Point[]{
                    new Point(x, y),
                    new Point(x - 1, y - 1),
                    new Point(x - 1, y),
                    new Point(x - 1, y + 1),
                    new Point(x, y - 1),
                    new Point(x, y + 1),
                    new Point(x + 1, y - 1),
                    new Point(x + 1, y),
                    new Point(x + 1, y + 1),

            };
        } else {
            offsetPoint = new Point[]{
                    new Point(x, y)
            };
        }

        for (int i = 0; i < size; i++) {
            int _x = offsetPoint[i].x;
            int _y = offsetPoint[i].y;
            if (_x >= 0 && _x < Width && _y >= 0 && _y < Height) {
                int location = _x * 4 + _y * RowStride;
                if (Abs((ScreenData[location] & 0xff) - description[2]) <= similarity_R) {
                    if (Abs((ScreenData[location + 1] & 0xff) - description[3]) <= similarity_G) {
                        if (Abs((ScreenData[location + 2] & 0xff) - description[4]) <= similarity_B) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    private boolean CompareColorEx(int[][] description, int sim, int x, int y, int offset) {
        for (int[] i : description) {
            int[] _description = Arrays.copyOf(i, i.length);
            _description[0] = _description[0] + x;
            _description[1] = _description[1] + y;
            if (!CompareColor(_description, sim, offset)) {
                return false;
            }
        }
        return true;
    }

    public boolean CompareColorEx(int[][] description, int sim, int offset) {
        for (int[] i : description) {
            if (!CompareColor(i, sim, offset)) {
                return false;
            }
        }
        return true;
    }

    public boolean CompareColorExLoop(int[][] description, int sim, int offset, long timeout, long timelag, int sign) throws InterruptedException {
        int num = (int) (timeout / timelag);
        if (sign == 0) {
            for (int i = 0; i < num; i++) {
                if (KeepScreen(false)) {
                    if (CompareColorEx(description, sim, offset)) {
                        return true;
                    }
                }
                Thread.sleep(timelag);
            }
        } else {
            for (int i = 0; i < num; i++) {
                if (KeepScreen(false)) {
                    if (!CompareColorEx(description, sim, offset)) {
                        return true;
                    }
                }
                Thread.sleep(timelag);
            }
        }
        return false;
    }

    private Point FindMultiColor2(int startX, int startY, int endX, int endY, int[] firstDescription, int[][] offsetDescription, int sim, int offset) {
        int r = firstDescription[2];
        short[] list = RedList[r];
        if (list != null) {
            int location;
            for (int i = 0, length = Steps[r] - 2; i < length; i += 2) {
                if (list[i] >= startX && list[i] <= endX && list[i + 1] >= startY && list[i + 1] <= endY) {
                    location = list[i + 1] * RowStride + list[i] * 4;
                    if (Abs((ScreenData[location + 1] & 0xff) - firstDescription[3]) <= firstDescription[6]) {
                        if (Abs((ScreenData[location + 2] & 0xff) - firstDescription[4]) <= firstDescription[7]) {
                            if (CompareColorEx(offsetDescription, list[i], list[i + 1], sim, offset)) {
                                return new Point(list[i], list[i + 1]);
                            }
                        }
                    }
                } else if (list[i] > endX && list[i + 1] > endY) {
                    return new Point(-1, -1);
                }
            }
        }
        return new Point(-1, -1);
    }

    public Point FindMultiColor(int startX, int startY, int endX, int endY, int[] firstDescription, int[][] offsetDescription, int sim, int offset) {
        startX = Math.max(startX, 0);
        startY = Math.max(startY, 0);
        endX = endX < Width ? endX : Width - 1;
        endY = endY < Height ? endY : Height - 1;
        int[] _firstDescription = new int[8];
        System.arraycopy(firstDescription, 0, _firstDescription, 0, 8);
        int similarity = (int) (255 - 255 * (sim / 100.0));
        _firstDescription[5] = similarity + firstDescription[5];
        _firstDescription[6] = similarity + firstDescription[6];
        _firstDescription[7] = similarity + firstDescription[7];
        boolean step = true;
        for (int i = 0; i <= _firstDescription[5]; i++) {
            int num;
            if (step) {
                num = firstDescription[2] + i;
                if (i != 0) {
                    i--;
                    step = false;
                }
            } else {
                num = firstDescription[2] - i;
                step = true;
            }
            if (num < 256 && num > -1) {
                _firstDescription[2] = num & 0xff;
                Point point = FindMultiColor2(startX, startY, endX, endY, _firstDescription, offsetDescription, similarity, offset);
                if (point.x != -1) {
                    return point;
                }
            }
        }
        return new Point(-1, -1);
    }

    public List<Point> FindMultiColorEx(int startX, int startY, int endX, int endY, int[] firstDescription, int[][] offsetDescription, int orientation, int sim, int offset) {
        List<Point> result = new ArrayList<>();
        startX = Math.max(startX, 0);
        startY = Math.max(startY, 0);
        endX = endX < Width ? endX : Width - 1;
        endY = endY < Height ? endY : Height - 1;
        int[] _firstDescription = new int[8];
        System.arraycopy(firstDescription, 0, _firstDescription, 0, 8);
        int similarity = (int) (255 - 255 * (sim / 100.0));
        _firstDescription[5] = similarity + firstDescription[5];
        _firstDescription[6] = similarity + firstDescription[6];
        _firstDescription[7] = similarity + firstDescription[7];
        boolean step = true;
        for (int i = 0; i <= _firstDescription[5]; i++) {
            int num;
            if (step) {
                num = firstDescription[2] + i;
                if (i != 0) {
                    i--;
                    step = false;
                }
            } else {
                num = firstDescription[2] - i;
                step = true;
            }
            if (num < 256 && num > -1) {
                _firstDescription[2] = num & 0xff;
                Point point = FindMultiColor2(startX, startY, endX, endY, _firstDescription, offsetDescription, similarity, offset);
                if (point.x != -1) {
                    result.add(point);
                }
            }
        }
        return result;
    }

    public Point FindMultiColorLoop(int startX, int startY, int endX, int endY, int[] firstDescription, int[][] offsetDescription, int sim, int offset, long timeout, long timelag, int sign) throws InterruptedException {
        int num = (int) (timeout / timelag);
        if (sign == 0) {
            for (int i = 0; i < num; i++) {
                if (KeepScreen(true)) {
                    Point result = FindMultiColor(startX, startY, endX, endY, firstDescription, offsetDescription, sim, offset);
                    if (result.x != -1) {
                        return result;
                    }
                }
                Thread.sleep(timelag);
            }
        } else {
            for (int i = 0; i < num; i++) {
                if (KeepScreen(true)) {
                    Point result = FindMultiColor(startX, startY, endX, endY, firstDescription, offsetDescription, sim, offset);
                    if (result.x == -1) {
                        return result;
                    }
                }
                Thread.sleep(timelag);
            }
        }
        return FindMultiColor(startX, startY, endX, endY, firstDescription, offsetDescription, sim, offset);
    }

    public boolean CompareColorExEx(int[][] description, int sim, int x, int y, int offset) {
        for (int[] _compareColor : description) {
            int[] compareColor = Arrays.copyOf(_compareColor, _compareColor.length);
            compareColor[0] = compareColor[0] + x;
            compareColor[1] = compareColor[1] + y;
            // 第5个参数，如果1的话就表示该点匹配上了为真，如果0的话表示该点未匹配上为真
            if ((1 == compareColor[5] && !CompareColor(compareColor, sim, offset))
                    || (0 == compareColor[5] && CompareColor(compareColor, sim, offset))) {
                return false;
            }
        }
        return true;
    }

}
